package com.fine.hair.manage.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fine.hair.comm.dto.AddUserDTO;
import com.fine.hair.comm.dto.CalendarConfigListDTO;
import com.fine.hair.comm.dto.InfoListDTO;
import com.fine.hair.comm.dto.ModifyRemarkDTO;
import com.fine.hair.comm.exception.BusinessException;
import com.fine.hair.comm.utils.ApiResponse;
import com.fine.hair.comm.utils.PageInfo;
import com.fine.hair.comm.vo.InfoListVO;
import com.fine.hair.comm.model.Calendar;
import com.fine.hair.comm.model.Order;
import com.fine.hair.comm.model.User;
import com.fine.hair.manage.mapper.CalendarMapper;
import com.fine.hair.manage.mapper.OrderMapper;
import com.fine.hair.manage.mapper.UserMapper;
import com.fine.hair.manage.service.UserService;
import com.fine.hair.manage.util.JwtUtil;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p></p>
 *
 * @author mouseyCat
 * @date 2021/1/26 21:40
 */
@Api(tags = {"周期管理"})
@RestController
@RequestMapping("/calendar/")
public class CalendarController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CalendarMapper calendarMapper;

    @Autowired
    private Snowflake snowflake;

    @Autowired
    private JwtUtil jwtUtil;

    @ApiOperation("周期管理的人数")
    @GetMapping("count")
    public ApiResponse count() {
        List<Calendar> calendars = calendarMapper.selectList(Wrappers.emptyWrapper());
        for (Calendar calendar : calendars) {
            Integer count = userMapper.selectCount(new LambdaQueryWrapper<User>().eq(User::getLabelType,
                    calendar.getId()));
            calendar.setPersonCount(count);
        }
        return ApiResponse.ofSuccess(calendars);
    }

    @Autowired
    private OrderMapper orderMapper;

    @ApiOperation("获取指定标签的用户列表")
    @PostMapping("info-list")
    public ApiResponse<ArrayList<InfoListVO>> infoList(@RequestBody InfoListDTO dto) {
        ArrayList<InfoListVO> users = Lists.newArrayList();
        List<User> list;
        if (!StringUtils.hasLength(dto.getRemarks())) {
            list = userMapper.selectList(new LambdaQueryWrapper<User>());
        } else {
            list = userMapper.selectList(new LambdaQueryWrapper<User>().like(User::getRemark, dto.getRemarks()));
        }
        if (list.size() > 0) {
            List<User> userList =
                    list.stream().filter(u -> dto.getConfigCode().equals(u.getLabelType())).collect(Collectors.toList());
            for (User user : userList) {
                InfoListVO infoListVO = new InfoListVO();
                infoListVO.setAvatar(user.getHeadPhoto());
                infoListVO.setName(user.getNickName());
                infoListVO.setRemark(user.getRemark());
                infoListVO.setUserId(user.getId());
                infoListVO.setCallTime(user.getCallTime());
                infoListVO.setUpdateBy(user.getUpdateBy());
                infoListVO.setPhone(user.getPhoneNumber());
                List<Order> orders = orderMapper.selectList(new LambdaQueryWrapper<Order>().eq(Order::getUserId,
                        user.getId()).orderByDesc(Order::getCreateTime));
                if (orders.size() > 0) {
                    Order order = orders.get(orders.size() - 1);
                    infoListVO.setCreateTime(DateUtil.formatDateTime(order.getCreateTime()));
                    infoListVO.setExecuteTime(DateUtil.formatDateTime(order.getExecuteTime()));
                    infoListVO.setItemImage(order.getItemImage());
                    infoListVO.setItemPrice(order.getItemPrice().toString());
                    infoListVO.setItemTitle(order.getItemTitle());
                }
                users.add(infoListVO);
            }
        }
        return ApiResponse.ofSuccess(users);
    }

    @ApiOperation("修改用户的备注")
    @PostMapping("modify-remark")
    public ApiResponse modifyRemark(@RequestBody ModifyRemarkDTO dto) {
        User user = userService.getById(dto.getUserId());
        if (ObjectUtil.isNull(user)) {
            throw new BusinessException("当前用户不存在");
        }
        user.setRemark(dto.getRemark());
        userService.updateById(user);
        return ApiResponse.ofSuccess();
    }

    @ApiOperation("添加用户到标签")
    @PostMapping("add-user")
    public ApiResponse addUser(@RequestBody AddUserDTO dto) {
        User user = userService.getById(dto.getUserId());
        if (ObjectUtil.isNull(user)) {
            throw new BusinessException("当前用户不存在");
        }
        user.setLabelType(dto.getConfigCode());
        userService.updateById(user);
        return ApiResponse.ofSuccess();
    }


    @ApiOperation("周期配置列表")
    @PostMapping("calendar-config-list")
    public ApiResponse calendarConfigList(@RequestBody CalendarConfigListDTO dto) {
        PageInfo<Calendar> pageInfo = new PageInfo<>(dto.getPageCurr(), dto.getPageSize());
        IPage<Calendar> page = calendarMapper.selectPage(pageInfo, new LambdaQueryWrapper<Calendar>().eq(Calendar::getStatus, 0));
        for (Calendar calendar : page.getRecords()) {
            Integer count = userMapper.selectCount(new LambdaQueryWrapper<User>().eq(User::getLabelType,
                    calendar.getId()));
            calendar.setPersonCount(count);
        }
        return ApiResponse.ofSuccess(page);
    }

    @ApiOperation("新增-修改周期配置，新增不传id")
    @PostMapping("add-calendar-config")
    public ApiResponse addCalendarConfig(@RequestBody Calendar calendar) {
        if (ObjectUtil.isNull(calendar.getId())) {
            calendar.setId(snowflake.nextId());
            calendarMapper.insert(calendar);
        } else {
            calendarMapper.updateById(calendar);
        }
        return ApiResponse.ofSuccess();
    }

    @ApiOperation("周期打电话更新,id->周期id，uid->用户id")
    @PutMapping("call/{id}/{uid}")
    public ApiResponse call(HttpServletRequest request, @PathVariable Long id, @PathVariable String uid) {
        String username = jwtUtil.getUsernameFromJWT(jwtUtil.getJwtFromRequest(request));
        User user = new User();
        user.setId(uid);
        user.setCallTime(new Date());
        user.setUpdateBy(username);
        userMapper.updateById(user);
        return ApiResponse.ofSuccess();
    }

    @ApiOperation("删除周期配置")
    @GetMapping("del-calendar-config/{id}")
    public ApiResponse delCalendarConfig(@PathVariable String id) {
        Calendar calendar = calendarMapper.selectById(id);
        if (ObjectUtil.isNull(calendar)) {
            throw new BusinessException("当前配置不存在");
        }
        List<User> users = userMapper.selectList(new LambdaQueryWrapper<User>().eq(User::getLabelType, id));
        if (users.size() > 0) {
            throw new BusinessException("当前周期配置内还有用户，不可删除");
        }
        calendar.setStatus(1);
        calendarMapper.updateById(calendar);
        return ApiResponse.ofSuccess();
    }


}
